package util;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.locks.InterProcessLock;
import org.apache.curator.framework.recipes.locks.InterProcessSemaphoreMutex;
import org.apache.curator.retry.ExponentialBackoffRetry;

/**
 * Created by yzy on 2020-01-09 15:13
 */
public class ZkLockUtil {

    private static CuratorFramework client;

    static {
        String connectString = "lg.main.zookeeper.bjc.001.lagou.com:2181,lg.main.zookeeper.bjc.002.lagou.com:2181,lg.main.zookeeper.bjc.003.lagou.com:2181";
        RetryPolicy retry = new ExponentialBackoffRetry(1000, 3);
        client = CuratorFrameworkFactory.newClient(connectString, 60000, 15000, retry);
        client.start();
    }

    /**
     * 获取分布式锁
     *
     * @param lockPath
     * @return
     */
    public static InterProcessLock getLock(String lockPath) {
        return new InterProcessSemaphoreMutex(client, lockPath);
    }

}
